﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Steve.UI.Models;
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel.Composition;

namespace Steve.UI.Controllers
{
    public class AccountControllerBase : Controller
    {
        [Import]
        public IAccountService Account { get; set; }

        public virtual ActionResult LogOff()
        {
            Account.SignOut();

            return RedirectToRoute("Home");
        }

        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")]
        public virtual ActionResult LogOn(string returnUrl, bool? notMe)
        {
            var model = new LogOnModel();

            model.ReturnUrl = returnUrl;

            if (notMe.HasValue && notMe.Value)
            {
                Account.ClearUser();
            }
            else
            {
                var u = Account.GetUser();

                if (u != null)
                {
                    model.UserName = u.UserName;
                    model.IsUnauthenticatedUserName = true;
                }
            }
            
            return View("LogOn", model);
        }

        [HttpPost]
        [ActionName("LogOn")]
        public virtual ActionResult LogOnPost(LogOnModel model)
        {
            if (model == null) throw new ArgumentNullException("model");

            if (ModelState.IsValid)
            {
                if (Account.ValidateUser(model.UserName, model.Password))
                {
                    Account.SignIn(model.UserName);

                    if (!string.IsNullOrWhiteSpace(model.ReturnUrl))
                    {
                        return Redirect(model.ReturnUrl);
                    }
                    else
                    {
                        return RedirectToRoute("Home");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
                }
            }

            var u = Account.GetUser();

            if (u != null && u.UserName == model.UserName)
            {
                model.IsUnauthenticatedUserName = true;
            }

            return View("LogOn", model);
        }
    }
}
